package com.roin.learn.activiti.controller;

import com.roin.learn.activiti.entity.Page;
import com.github.pagehelper.util.StringUtil;
import com.roin.learn.activiti.entity.ResourceResult;
import com.roin.learn.activiti.entity.User;
import com.roin.learn.activiti.service.ProcessService;
import com.roin.learn.activiti.service.UserService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假申请
 */
@Controller
@RequestMapping("leave")
public class LeaveController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    ProcessService processService;
    @Resource
    ManagementService managementService;
    @Resource
    TaskService taskService;
    @Resource
    RepositoryService repositoryService;
    @Resource
    UserService userService;
    @Resource
    ProcessEngineConfiguration processEngineConfiguration;

    @RequestMapping("main.htm")
    public ModelAndView toMain(){
        ModelAndView mav = new ModelAndView("leave/main");
        List<ProcessInstance> processInstanceList = processService.getProcessInstanceList("QingJiaShenQingProcess");
        mav.addObject("processInstanceList",processInstanceList);
        try {
            List<Task> taskList = processService.queryTaskList("QingJiaShenQingProcess");
            mav.addObject("taskList",taskList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page<User> users = userService.getDtoPage(1,999999,null);
        mav.addObject("users",users.getList());
        return mav;
    }

    /**
     * 发起流程
     * @param key
     * @param userId 发起人
     * @return
     */
    @RequestMapping("/start.do")
    @ResponseBody
    public ResourceResult start(String key, Integer userId) {
        ResourceResult result = new ResourceResult();
        if (StringUtil.isEmpty(key))
            result.setMessage( "发起失败!key参数为空！");
        if (userId==null)
            result.setMessage( "发起失败!userId参数为空！");
        if (StringUtil.isEmpty(result.getMessage())) {
            try {
                User user = userService.getById(userId);
                Map<String, Object> jsnVariables = new HashMap<String, Object>();
                jsnVariables.put("userId",user.getUserId());
                jsnVariables.put("positionId",user.getPositionId());
                ProcessInstance instance = processService.startProessInstance(key, null, jsnVariables);
                Task task = processService.queryActiviTask(instance.getProcessInstanceId(),user.getUserId());
                if (task!=null)
                    processService.completeTask(task.getId(),jsnVariables);
                result.setSuccess(instance!=null);
                result.setMessage(result.isSuccess() ? "发起成功！" : "发起失败!");
            }catch (Exception e){
                log.error("发起流程出错",e);
                result.setMessage("发起失败!");
            }

        }
        return result;
    }
    /**
     * 审批
     * @param taskId
     * @param action 审批意见 1同意 0，不同意
     * @return
     */
    @RequestMapping("/handle.do")
    @ResponseBody
    public ResourceResult handle(String taskId, Integer action) {
        ResourceResult result = new ResourceResult();
        if (StringUtil.isEmpty(taskId))
            result.setMessage( "审批失败!taskId参数为空！");
        if (action==null)
            result.setMessage( "审批失败!action参数为空！");
        if (StringUtil.isEmpty(result.getMessage())) {
            try {
                Task task = processService.queryTaskById(taskId);
                Map<String, Object> jsnVariables = new HashMap<>();
                jsnVariables.put("action",action);
                if (task!=null)
                    processService.completeTask(task.getId(),jsnVariables);
                result.setSuccess(true);
                result.setMessage(result.isSuccess() ? "审批成功！" : "审批失败!");
            }catch (Exception e){
                log.error("审批请假流程出错",e);
                result.setMessage("审批失败!");
            }

        }
        return result;
    }
    /**
     * 查看流程实例的历史活动
     * @param processInstanceId 流程实例ID
     * @return
     */
    @RequestMapping("/historyTask.htm")
    @ResponseBody
    public ModelAndView historyTask(@RequestParam(required = true) String processInstanceId) {
        ModelAndView mav = new ModelAndView("leave/historyTask");
        try {
            List<HistoricActivityInstance> historicActivityInstances= processService.getHistoricActivityInstance(processInstanceId,null);
            mav.addObject("historicActivityInstances",historicActivityInstances);
        }catch (Exception e){
            log.error("查看流程实例的历史活动出错",e);
        }
        return mav;
    }

    /**
     * 通过流程定义ID或者流程实例ID或者任务ID查看流程图
     * @param processDefinitionId 流程定义ID
     * @param executionId 流程实例ID
     * @param response
     */
    @RequestMapping("/graph.htm")
    public void showGraphById(@RequestParam(required = true)String processDefinitionId, @RequestParam(required = true)String executionId, HttpServletResponse response){
        response.setContentType("image/jpg");
        OutputStream out=null;
        try {
            out = response.getOutputStream();
                InputStream is = processService.processTracking(processDefinitionId,executionId);
                int len = 0;
                byte[] b = new byte[1024];
                while ((len = is.read(b, 0, 1024)) != -1) {
                    out.write(b, 0, len);
                }
            out.flush();
        }catch (Exception e){
            log.error("显示流程图出错",e);
        }finally {
            try {
                if (out!=null)
                    out.close();
            } catch (IOException e) {
                log.error("显示流程图出错",e);
            }
        }

    }
}
